import { ConfigService } from '@nestjs/config'
import { PrismaClient } from '@prisma/client'
import { Request } from 'express'
/**
 * 封装的分页函数
 * @param {string} model prisma模型名称
 * @param {any} query 分页查询条件
 * @returns
 */
export async function pageData<T>(model: string, query: any): Promise<Result.pageData<T>> {
  const config = new ConfigService()
  const prisma = new PrismaClient()
  const row = config.get('PAGE_ROW')
  const params = {} as T
  Object.keys(query).forEach((key) => {
    if (key !== 'page' && query[key]) {
      params[key] = query[key]
    }
  })
  const dataList = (await prisma[model].findMany({
    where: {
      ...params,
    },
    orderBy: {
      createdAt: 'desc',
    },
    skip: (+query.page - 1) * row,
    take: +row,
  })) as T[]
  const total = await prisma[model].count({
    where: {
      ...params,
    },
  })
  return {
    currentPage: +query.page,
    pageRow: +row,
    total,
    totalPage: Math.ceil(total / row),
    data: dataList,
  }
}

/**
 * 获取当前时间格式化
 * @returns
 */
export function getCurrentDateTime() {
  // 创建当前时间的 Date 对象
  let currentDate = new Date()

  // 获取年份、月份和日期
  let year = currentDate.getFullYear()
  let month = ('0' + (currentDate.getMonth() + 1)).slice(-2) // 月份从0开始，因此需要加1
  let day = ('0' + currentDate.getDate()).slice(-2)

  // 获取小时、分钟和秒
  let hours = ('0' + currentDate.getHours()).slice(-2)
  let minutes = ('0' + currentDate.getMinutes()).slice(-2)
  let seconds = ('0' + currentDate.getSeconds()).slice(-2)

  // 格式化日期和时间字符串
  let formattedDate = year + '-' + month + '-' + day
  let formattedTime = hours + ':' + minutes + ':' + seconds

  // 拼接日期和时间
  let dateTime = formattedDate + ' ' + formattedTime

  // 返回拼接后的日期和时间字符串
  return dateTime
}

/**
 * 解析Request属性
 * @param req
 * @returns
 */
export function getInfoFromReq(req: Request) {
  const { method, originalUrl: url, body, query, params, ip } = req
  return {
    method,
    url,
    body,
    query,
    params,
    ip,
  }
}
